import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { Table, Space, Button, Modal, Drawer } from "antd";
import { confirm } from '@tauri-apps/plugin-dialog';
import { PlusOutlined, ImportOutlined } from '@ant-design/icons';
import { open, save } from '@tauri-apps/plugin-dialog';

import { FlowProject, flowGetProjects } from '../../../../services';
import { TaskEditor } from '.';
import { dsDeleteById, dsFind, Task } from '@/services/local';
import { SCHEDULER_TASK_CLASS_IDENTIFIER } from '@/services/constants';
import { TaskResultTable } from '../result';

export interface TasksTableProps {
    style?: CSSProperties;
}


const dateNumberToStr = (date: number): string => {
    let str = date + '';

    let res = '';
    for (let i = 0; i < str.length; i++) {
        let t = str[i];
        if (i > 3 && i % 2 == 0) {
            res = res + '-';
        }
        res = res + t;
    }
    return res;
}

export const TasksTable: React.FC<TasksTableProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [resultsOpen, setResultsOpen] = useState<boolean>(false);

    const [tasks, setTasks] = useState<Array<Task>>([]);

    const [selected, setSelected] = useState<Task | null>(null);

    const [page, setPage] = useState<number>(1);

    const [pageSize, setPageSize] = useState<number>(10);

    const [total, setTotal] = useState<number>(0);

    const refresh = async (page: number, pageSize: number) => {
        setLoading(true);
        try {
            const { total, data } = await dsFind(0, SCHEDULER_TASK_CLASS_IDENTIFIER, {});
            setTotal(total);
            //时间处理
            setTasks(data.map((item, index) => {
                return {
                    ...item,
                    start_time: dateNumberToStr(item.start_time),
                    end_time: dateNumberToStr(item.start_time),
                }
            }));
        } catch (error) {
            console.error(error);
        }
        setLoading(false);
    };

    const columns = [
        {
            title: '名称',
            dataIndex: 'title',
            key: 'title',
            ellipsis: true,
        },
        {
            title: '模板',
            dataIndex: 'template_identifier',
            key: 'template_identifier',
            ellipsis: true,
        },
        {
            title: 'Cron',
            dataIndex: 'cron',
            key: 'cron',
        },
        {
            title: '备注',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: '操作',
            key: '操作',
            width: '220px',
            render: (_, record) => {
                return (
                    <Space size="middle">
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                setSelected(record);
                                setIsModalOpen(true);
                            }}
                        >编辑</Button>
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                setSelected(record);
                                setResultsOpen(true);
                            }}
                        >执行记录</Button>
                        <Button
                            type={'link'}
                            size={'small'}
                            onClick={async () => {
                                //
                                const confirmed2 = await confirm('确定是否删除该域？', { title: '删除', kind: 'warning' });
                                if (confirmed2) {

                                    let res = await dsDeleteById(0, SCHEDULER_TASK_CLASS_IDENTIFIER, record.id);

                                    //
                                    await refresh(page, pageSize);
                                }
                            }}
                        >删除</Button>
                    </Space>
                );
            }
        },
    ];

    useEffect(() => {
        refresh(page, pageSize);
    }, [page, pageSize]);

    return (
        <Container style={props.style}>
            <Buttons>
                <Button style={{ width: '90px' }} loading={loading} type={'primary'} icon={<PlusOutlined />}
                    onClick={async () => {
                        setSelected(null);
                        setIsModalOpen(true);
                    }}
                >添加</Button>
            </Buttons>
            <Table
                bordered
                loading={loading}
                rowKey={'identifier'}
                pagination={{
                    showSizeChanger: true,
                    total: total,
                    current: page,
                    pageSize: pageSize,
                    onChange: (page, pageSize) => {
                        setPage(page);
                    },
                    onShowSizeChange: (current, size) => {
                        setPageSize(size);
                    }
                }}
                dataSource={tasks}
                columns={columns}
            />
            <Modal
                styles={{
                    content: {
                        minWidth: '600px',
                        minHeight: '400px'
                    }
                }}
                title="添加数据流"
                footer={false}
                destroyOnClose={true}
                open={isModalOpen}
                onOk={async () => {
                    //刷新
                    await refresh(page, pageSize);
                    setIsModalOpen(false);
                }} onCancel={async () => {
                    //刷新
                    await refresh(page, pageSize);
                    setIsModalOpen(false);
                }}>
                <TaskEditor item={selected} onFinish={async () => {
                    //刷新
                    await refresh(page, pageSize);
                    setIsModalOpen(false);
                }}></TaskEditor>
            </Modal>
            <Drawer
                title="任务执行记录"
                onClose={() => {
                    setResultsOpen(false);
                }}
                footer={false}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={resultsOpen}>
                <TaskResultTable task_identifier={selected?.identifier}></TaskResultTable>
            </Drawer>
        </Container>
    );
}

const Container = styled.div`
    height: 100%;
    width: 100%;
`;

const Buttons = styled.div`
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding: 6px 6px;
    gap:10px;
`;
